package com.anssy.voteballot.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.anssy.voteballot.MainActivity;
import com.anssy.voteballot.R;
import com.anssy.voteballot.base.BaseActivity;
import com.anssy.voteballot.bean.ConfigVoteRes;
import com.anssy.voteballot.bean.PushBean;
import com.anssy.voteballot.bean.TopicsListRes;
import com.anssy.voteballot.constant.ConstantValue;
import com.anssy.voteballot.dialog.UserInfoDialog;
import com.anssy.voteballot.http.Api;
import com.anssy.voteballot.http.HttpService;
import com.anssy.voteballot.utils.CurrencyUtils;
import com.anssy.voteballot.utils.DeviceUtils;
import com.anssy.voteballot.utils.DownloadUtil;
import com.anssy.voteballot.utils.HttpUtils;
import com.anssy.voteballot.utils.VersionUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TopicsListActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = TopicsListActivity.class.getSimpleName();
    private static final int TYPE_ZERO = 0;
    private static final int TYPE_ONE = 1;
    private static final int TYPE_TWO = 2;
    private static final int TYPE_THREE = 3;
    private static final int TYPE_FOUR = 4;
    //0初始化，1开始投票，2停止投票
    private static final String DEFAULT_STATUS = "0";
    private static final String START_STATUS = "1";
    private static final String FINISH_STATUS = "2";
    private RecyclerView mRecyclerView;
    private TextView mTvVersionCode;
    private TextView mTvDeviceId;
    private TopicsListRes topicsListRes;
    private MyAdapter myAdapter;
    private TextView mTvSecondTitle;
    private TextView mTvTitle;
    private TextView mTvNetStatus;
    private TextView mTvPeopleNum;
    private boolean isVoteing;

    @Override
    public void onBackPressed() {
        if (!isVoteing) {
            super.onBackPressed();
        } else {
            ToastUtils.showShort("正在表决中");
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        getDataFromServer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String message) {
        LogUtils.v(TAG, "message--" + message);
        if (!TextUtils.isEmpty(message)) {
            PushBean pushBean = new Gson().fromJson(message, PushBean.class);
            if (pushBean != null && pushBean.getType() != null) {
                if (pushBean.getType().equals("3")) {
                    if (topicsListRes.getThisState() == 2) {
                        if (Integer.parseInt(pushBean.getSubjectType()) == TYPE_ZERO) {
                            Intent intent = new Intent(TopicsListActivity.this, AnswerOneActivity.class);
                            intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingSubId()));
                            startActivity(intent);
                        } else if (Integer.parseInt(pushBean.getSubjectType()) == TYPE_ONE) {
                            Intent intent = new Intent(TopicsListActivity.this, AnswerTwoSingleActivity.class);
                            intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingSubId()));
                            startActivity(intent);
                        } else if (Integer.parseInt(pushBean.getSubjectType()) == TYPE_TWO) {
                            Intent intent = new Intent(TopicsListActivity.this, AnswerTwoMultiActivity.class);
                            intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingSubId()));
                            startActivity(intent);
                        } else if (Integer.parseInt(pushBean.getSubjectType()) == TYPE_THREE) {
                            Intent intent = new Intent(TopicsListActivity.this, AnswerThreeActivity.class);
                            intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingSubId()));
                            startActivity(intent);
                        } else if (Integer.parseInt(pushBean.getSubjectType()) == TYPE_FOUR) {
                            Intent intent = new Intent(TopicsListActivity.this, AnswerFourActivity.class);
                            intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingSubId()));
                            startActivity(intent);
                        }
                    }
                } else if (pushBean.getType().equals("4")) {
                    getDataFromServer();
                }
            }
        }
    }


    @Override
    public int setLayoutResource() {
        return R.layout.activity_topic_list;
    }

    @Override
    public void initView() {
        mTvTitle = findViewById(R.id.tv_title);
        mTvSecondTitle = findViewById(R.id.tv_second_title);
        mRecyclerView = findViewById(R.id.rv_topic_list);
        mTvDeviceId = findViewById(R.id.tv_device_id);
        mTvVersionCode = findViewById(R.id.tv_version_code);
        mTvNetStatus = findViewById(R.id.tv_net_status);
        mTvPeopleNum = findViewById(R.id.tv_people_num);
    }

    @Override
    public void initData() {
        setBottomData();
    }


    @SuppressLint("SetTextI18n")
    private void setBottomData() {
        CurrencyUtils.checkNetStatus(mTvNetStatus);
        if (!TextUtils.isEmpty(VersionUtils.getVersion(TopicsListActivity.this))) {
            mTvVersionCode.setText("版本号:v" + VersionUtils.getVersion(TopicsListActivity.this));
        }
        mTvDeviceId.setText("设备ID:" + DeviceUtils.getUniqueId(TopicsListActivity.this));

    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        private final Context context;

        public MyAdapter(Context context) {
            this.context = context;
        }

        @NonNull
        @Override
        public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_rv_topics_list, parent, false);
            return new MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
            if (!TextUtils.isEmpty(topicsListRes.getDatas().getListSubs().get(position).getSubContent())) {
                holder.mTvName.setText(position + 1 + "." + topicsListRes.getDatas().getListSubs().get(position).getSubContent());
            } else {
                holder.mTvName.setText("");
            }
            holder.mRvOthers.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            holder.mRvOthers.setAdapter(new MyOtherAdapter(context, topicsListRes.getDatas().getListSubs().get(position).getListFujian()));
            if (topicsListRes.getThisState() == 1) {
                if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 0) {
                    holder.mBtnVote.setText("发起表决");
                } else if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 1) {
                    holder.mBtnVote.setText("表决中");
                    if (topicsListRes.getDatas().getListSubs().get(position).getVoteing() && !topicsListRes.getDatas().getListSubs().get(position).getFinish()) {
                        holder.mBtnVote.setText(String.valueOf(topicsListRes.getDatas().getListSubs().get(position).getSecond()));
                    } else if (!topicsListRes.getDatas().getListSubs().get(position).getVoteing() && topicsListRes.getDatas().getListSubs().get(position).getFinish()) {
                        LogUtils.v(TAG, "主持端-表决结束");
                        Api.getRetrofit().create(HttpService.class).configVote(DeviceUtils.getUniqueId(context), topicsListRes.getDatas().getListSubs().get(position).getMeettingId()
                                , topicsListRes.getDatas().getListSubs().get(position).getId(), "0", FINISH_STATUS).enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                                isVoteing = false;
                                ConfigVoteRes configVoteRes = (ConfigVoteRes) HttpUtils.parseResponse(response, ConfigVoteRes.class);
                                if (configVoteRes != null && configVoteRes.getCode() == 200) {
                                    holder.mBtnVote.setText("表决结束");
                                }
                            }

                            @Override
                            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                                t.printStackTrace();
                            }
                        });

                    }
                } else if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 2) {
                    holder.mBtnVote.setText("表决结束");
                }
            } else if (topicsListRes.getThisState() == 2) {
                if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 0) {
                    holder.mBtnVote.setText("暂未开启投票");
                } else if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 1) {
                    holder.mBtnVote.setText("投票中");
//                    if (topicsListRes.getDatas().getListSubs().get(position).getVoteing() && !topicsListRes.getDatas().getListSubs().get(position).getFinish()) {
//                        holder.mBtnVote.setText(String.valueOf(topicsListRes.getDatas().getListSubs().get(position).getSecond()));
//                    } else {
//                        holder.mBtnVote.setText("投票结束");
//                    }
                } else if (topicsListRes.getDatas().getListSubs().get(position).getOPenClosed() == 2) {
                    holder.mBtnVote.setText("投票结束");
                }
            }
            holder.mBtnVote.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (holder.mBtnVote.getText().toString().trim().equals("发起表决")) {
                        UserInfoDialog userInfoDialog = new UserInfoDialog(context);
                        userInfoDialog.show();
                        userInfoDialog.setClickListener(new UserInfoDialog.ClickListenerInterface() {
                            @Override
                            public void doConfirm(String time) {
                                Api.getRetrofit().create(HttpService.class).configVote(DeviceUtils.getUniqueId(context), topicsListRes.getDatas().getListSubs().get(position).getMeettingId()
                                        , topicsListRes.getDatas().getListSubs().get(position).getId(), time, START_STATUS).enqueue(new Callback<ResponseBody>() {
                                    @Override
                                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                                        ConfigVoteRes configVoteRes = (ConfigVoteRes) HttpUtils.parseResponse(response, ConfigVoteRes.class);
                                        if (configVoteRes != null) {
                                            if (configVoteRes.getCode() == 200) {
                                                topicsListRes.getDatas().getListSubs().get(position).setoPenClosed(1);
                                                TimeCount timeCount = new TimeCount(Long.parseLong(time) * 1000, 1000, position);
                                                timeCount.start();
                                            } else {
                                                ToastUtils.showShort(configVoteRes.getMsg());
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                                        t.printStackTrace();
                                    }
                                });
                            }

                            @Override
                            public void doCancel() {

                            }
                        });
                    } else if (holder.mBtnVote.getText().toString().trim().equals("投票")) {
                        if (topicsListRes.getDatas().getListSubs().get(position).getSubjectType() == TYPE_ZERO) {
                            Intent intent = new Intent(context, AnswerOneActivity.class);
                            intent.putExtra(ConstantValue.ID, topicsListRes.getDatas().getListSubs().get(position).getId());
                            startActivity(intent);
                        } else if (topicsListRes.getDatas().getListSubs().get(position).getSubjectType() == TYPE_ONE) {
                            Intent intent = new Intent(context, AnswerTwoSingleActivity.class);
                            intent.putExtra(ConstantValue.ID, topicsListRes.getDatas().getListSubs().get(position).getId());
                            startActivity(intent);
                        } else if (topicsListRes.getDatas().getListSubs().get(position).getSubjectType() == TYPE_TWO) {
                            Intent intent = new Intent(context, AnswerTwoMultiActivity.class);
                            intent.putExtra(ConstantValue.ID, topicsListRes.getDatas().getListSubs().get(position).getId());
                            startActivity(intent);
                        } else if (topicsListRes.getDatas().getListSubs().get(position).getSubjectType() == TYPE_THREE) {
                            Intent intent = new Intent(context, AnswerThreeActivity.class);
                            intent.putExtra(ConstantValue.ID, topicsListRes.getDatas().getListSubs().get(position).getId());
                            startActivity(intent);
                        } else if (topicsListRes.getDatas().getListSubs().get(position).getSubjectType() == TYPE_FOUR) {
                            Intent intent = new Intent(context, AnswerFourActivity.class);
                            intent.putExtra(ConstantValue.ID, topicsListRes.getDatas().getListSubs().get(position).getId());
                            startActivity(intent);
                        }
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return topicsListRes.getDatas().getListSubs().size();
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {

            private final TextView mTvName;
            private final RecyclerView mRvOthers;
            private final Button mBtnVote;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                mTvName = itemView.findViewById(R.id.tv_name);
                mRvOthers = itemView.findViewById(R.id.rv_others);
                mBtnVote = itemView.findViewById(R.id.btn_vote);
            }
        }
    }

    class MyOtherAdapter extends RecyclerView.Adapter<MyOtherAdapter.MyOtherViewHolder> {

        private final Context context;
        private final List<TopicsListRes.DatasBeans.ListSubsBeans.ListFujianBeans> fujianBeans;

        public MyOtherAdapter(Context context, List<TopicsListRes.DatasBeans.ListSubsBeans.ListFujianBeans> fujianBeans) {
            this.context = context;
            this.fujianBeans = fujianBeans;
        }

        @NonNull
        @Override
        public MyOtherAdapter.MyOtherViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_rv_others, parent, false);
            return new MyOtherViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull MyOtherAdapter.MyOtherViewHolder holder, @SuppressLint("RecyclerView") int position) {
            if (!TextUtils.isEmpty(fujianBeans.get(position).getFileName())) {
                holder.mTvOthers.setText("附件" + position + 1 + ":" + fujianBeans.get(position).getFileName());
            } else {
                holder.mTvOthers.setText("");
            }
            holder.mTvOthers.setOnClickListener(view -> {
                if (!TextUtils.isEmpty(fujianBeans.get(position).getFilePath())) {
                    if (CurrencyUtils.checkWps(context)) {
                        openWps(ConstantValue.HOST + fujianBeans.get(position).getFilePath());
                    } else {
                        ToastUtils.showShort("暂未安装WPS");
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return fujianBeans.size();
        }

        public class MyOtherViewHolder extends RecyclerView.ViewHolder {

            private final TextView mTvOthers;

            public MyOtherViewHolder(@NonNull View itemView) {
                super(itemView);
                mTvOthers = itemView.findViewById(R.id.tv_others);
            }
        }
    }

    private void getDataFromServer() {
        Api.getRetrofit().create(HttpService.class).getSubList(DeviceUtils.getUniqueId(this), getIntent().getIntExtra(ConstantValue.ID, 0))
                .enqueue(new Callback<ResponseBody>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        topicsListRes = (TopicsListRes) HttpUtils.parseResponse(response, TopicsListRes.class);
                        if (topicsListRes != null) {
                            if (topicsListRes.getCode() == 200) {
                                if (topicsListRes.getThisState() == 1) {
                                    if (!TextUtils.isEmpty(getIntent().getStringExtra(ConstantValue.MEETING_NUM))) {
                                        mTvPeopleNum.setText("签到人数:" + getIntent().getStringExtra(ConstantValue.MEETING_NUM));
                                    }
                                }
                                if (!TextUtils.isEmpty(topicsListRes.getDatas().getTitle())) {
                                    mTvTitle.setText(topicsListRes.getDatas().getTitle());
                                }
                                if (!TextUtils.isEmpty(topicsListRes.getDatas().getSetFubiaoti())) {
                                    mTvSecondTitle.setText("———" + topicsListRes.getDatas().getSetFubiaoti());
                                }
                                mRecyclerView.setLayoutManager(new LinearLayoutManager(TopicsListActivity.this, LinearLayoutManager.VERTICAL, false));
                                myAdapter = new MyAdapter(TopicsListActivity.this);
                                mRecyclerView.setAdapter(myAdapter);
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @Override
    public void initListener() {
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {


            default:
                break;
        }
    }

    class TimeCount extends CountDownTimer {

        private final int position;

        public TimeCount(long millisInFuture, long countDownInterval, int position) {
            super(millisInFuture, countDownInterval);
            this.position = position;
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onTick(long millisUntilFinished) {
            isVoteing = true;
            LogUtils.v(TAG, millisUntilFinished);
            long readTime = millisUntilFinished / 1000;
            TopicsListRes.DatasBeans.ListSubsBeans datasBeans = topicsListRes.getDatas().getListSubs().get(position);
            datasBeans.setVoteing(true);
            datasBeans.setFinish(false);
            if (readTime >= 0) {
                datasBeans.setSecond(readTime);
            }
            if (myAdapter != null) {
                myAdapter.notifyItemChanged(position);
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onFinish() {
            TopicsListRes.DatasBeans.ListSubsBeans datasBeans = topicsListRes.getDatas().getListSubs().get(position);
            datasBeans.setVoteing(false);
            datasBeans.setFinish(true);
            datasBeans.setSecond(0);
            if (myAdapter != null) {
                myAdapter.notifyItemChanged(position);
            }
        }
    }

    private void openWps(String fileUrl) {
        if (!TextUtils.isEmpty(fileUrl)) {
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            LogUtils.v(TAG, "subString--" + fileName);
            File downloadFile = new File(Environment.getExternalStorageDirectory() + "/会议表决/", fileName);
            if (!downloadFile.exists()) {
                DownloadUtil downloadUtil = new DownloadUtil();
                downloadUtil.download(fileUrl
                        , "会议表决", fileName
                        , new DownloadUtil.OnDownloadListener() {
                            @Override
                            public void onDownloadSuccess(String fileNames) {
                                LogUtils.v(TAG, "onDownloadSuccess-----" + fileName);
                                runOnUiThread(() -> CurrencyUtils.openFile(TopicsListActivity.this, Environment.getExternalStorageDirectory() + "/会议表决/" + fileName));

                            }

                            @Override
                            public void onDownloading(int progress) {
                                LogUtils.v(TAG, "progress--" + progress);
                                runOnUiThread(() -> {
                                });
                            }

                            @Override
                            public void onDownloadFailed() {
                                LogUtils.v(TAG, "onDownloadFailed-----");
                                ToastUtils.showShort("下载失败");
                            }
                        });
            } else {
                CurrencyUtils.openFile(TopicsListActivity.this, Environment.getExternalStorageDirectory() + "/会议表决/" + fileName);
            }
        }
    }

}
